<?php

namespace App\Console\Commands;

use App\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class RefreshAdList extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'refresh:ad';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新广告列表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {
            $redis = Redis::connection();
            //构造随机队列
            $redis->del('random_order_list');
            Order::query()->where(['state' => Order::ORDER_STATE_ON, 'type' => 0])->inRandomOrder()->get()->each(function ($order) use ($redis) {
                $redis->rpush('random_order_list', serialize([
                    'order_id' => $order->id,
                    'url' => $order->url
                ]));
            });
            //构造竞价队列
            $redis->del('bidding_order_list');
            Order::query()->where(['state'=> Order::ORDER_STATE_ON, 'type' => 0])->orderByDesc('cpm')->get()->each(function ($order) use ($redis) {
                $redis->rpush('bidding_order_list', serialize([
                    'order_id' => $order->id,
                    'url' => $order->url
                ]));
            });
        } catch (\Exception $exception) {
            //写日志
            Log::error('刷新广告失败：' . $exception->getMessage());
        }
    }
}
